package com.woniu.woniu_bx.filter;

import com.woniu.woniu_bx.exception.ManagerExistsException;
import com.woniu.woniu_bx.mapper.ManagerMapper;
import com.woniu.woniu_bx.pojo.Manager;
import com.woniu.woniu_bx.pojo.Perm;
import com.woniu.woniu_bx.pojo.Role;
import com.woniu.woniu_bx.service.ManagerService;
import com.woniu.woniu_bx.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author zhangjin
 * @Date 2022/9/7 9:49
 */
@Component
@Slf4j
public class AuthUserDetailsService implements UserDetailsService {
    @Autowired
    private ManagerService managerService;

    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("username{}",username);
        Manager manager = managerService.getManagerByAccount(username);
        if (manager==null){
            throw new ManagerExistsException("账号不存在");
        }
        Role role = roleService.getRoleByID(manager.getRoleId());
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        for (Perm power : role.getPermList()) {
            list.add(new SimpleGrantedAuthority(power.getCode()));
        }
        return new AuthUser(manager.getId(), role.getId(), manager.getAccount(),manager.getPassword(),list);
    }
}
